package com.rainbow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainbow.common.UserUtils;
import com.rainbow.entity.User;
import com.rainbow.expetion.MyException;
import com.rainbow.mapper.UserMapper;
import com.rainbow.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author rainbow
 **/
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User hr = baseMapper.loadUserByUsername(s);
        if (hr == null) {
            throw new MyException("用户名不对");
        }
        return hr;
    }

    @Override
    public int hrReg(String username, String password) {
        //如果用户名存在，返回错误
        if (baseMapper.loadUserByUsername(username) != null) {
            return -1;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        return baseMapper.hrReg(username, encode);
    }

    @Override
    public List<User> getHrsByKeywords(String keywords) {
        return baseMapper.getHrsByKeywords(keywords);
    }

    @Override
    public int updateHr(User hr) {
        return baseMapper.updateHr(hr);
    }

    @Override
    public int updateHrRoles(Long hrId, Long[] rids) {
        int i = baseMapper.deleteRoleByHrId(hrId);
        return baseMapper.addRolesForHr(hrId, rids);
    }

    @Override
    public User getHrById(Long hrId) {
        return baseMapper.getHrById(hrId);
    }

    @Override
    public int deleteHr(Long hrId) {
        return baseMapper.deleteHr(hrId);
    }

    @Override
    public List<User> getAllHrExceptAdmin() {
        return baseMapper.getAllHr(UserUtils.getCurrentHr().getId());
    }

    @Override
    public List<User> getAllHr() {
        return baseMapper.getAllHr(null);
    }
}
